/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//
import wifi from '@ohos.wifi_native_js';
import prompt from '@system.prompt'
import '../../common/StringExtend.js'
import Subscriber from '@ohos.commonevent';

var mCommonEventSubscriber = null;
const mCommonEventSubscribeInfo = {
    events: ["usual.event.wifi.CONN_STATE"]
};
export default {
    data: {
        wifiInfo:{
            enable:false,
            isActive:false,
            statusCode:-1,
            scanInfo:[]//开发调试用无效数据{ssid:"123",securityType:0},{ssid:"234",securityType:1},{ssid:"234",securityType:1},{ssid:"234",securityType:1},{ssid:"234",securityType:1},{ssid:"234",securityType:1},{ssid:"234",securityType:1},{ssid:"234",securityType:1}
        },
        wifiPassword:'',
        wifichecked:{},
        connectItem:{},
        isScaning:false,
        isItemMoved:false,
        isKeyBoradShow:false,
        console:""
    },
    computed:{
        state(){
            let str="当前未连接";
            if(!this.wifiInfo.isActive){
                str="请先打开WIFI"
            }else{
                switch(this.wifiInfo.statusCode){
                    case 0:{
                        return "连接中或已连接但状态未改变";
                   }
                    case 1:
                    case 3:{
                        return `已连接：${this.connectItem.ssid.utf8ToStr()}`;
                   }
                    case 6:{
                        return `当前网络连接不可用：${this.connectItem.ssid.utf8ToStr()} `;
                    }
                    default:{
                        return "未连接";
                    }
                }
            }
            return str;
        },
        WifiScanList(){
            let list=this.wifiInfo.scanInfo;
            list=list.filter(t=>t.bssid!=this.connectItem.bssid && t.ssid);
            list.forEach(t=>{
                t.signalLevel=wifi.getSignalLevel(t.rssi,t.band) || 1;
            })
            return list.orderByDesc(t=>t.signalLevel);
        },
        checkedWifiName(){
            if(this.wifichecked && this.wifichecked.ssid){
                return this.wifichecked.ssid.utf8ToStr();
            }
            return "";
        }
    },
    onInit() {
        this.wifiInfo.isActive=wifi.isWifiActive();
        this.wifiInfo.isActive&&this.wifiScaning();
        this.wifiStatusListener();
    },
    //订阅WiFi状态
    wifiStatusListener() {
        Subscriber.createSubscriber(mCommonEventSubscribeInfo,
            this.CreateSubscriberCallBack.bind(this));
    },
    unSubscriberListener() {
        Subscriber.unsubscribe(mCommonEventSubscriber, () => {
            console.info('wifi unsubscribe');
        });
    },
    CreateSubscriberCallBack(err, data) {
        mCommonEventSubscriber = data;
        Subscriber.subscribe(mCommonEventSubscriber, this.SubscriberCallBack.bind(this));
    },

    SubscriberCallBack(err, data) {
        let eventName=data.event;
        let code = this.wifiInfo.statusCode=data.code;
        switch(code){
            case 0:{//连接中
                setTimeout(()=>{
                    this.hideInputPassword();
                },10000)
               break;
           }
            case 1://获取到IP
            case 3:{//连接成功
               this.connectItem=this.wifichecked
               this.hideInputPassword();
               break;
            }
            case 6:{//网络不可用
               this.hideInputPassword();
               break
            }
            case 9:{//连接失败
               prompt.showToast({
                   message:"连接失败，请检查密码是否正确",
                   duration:1500
               })
               break;
           }
            case 11:{//连接超时
                prompt.showToast({
                    message:"连接超时，请检查密码是否正确",
                    duration:1500
                })
                break;
            }
            default:{
                this.console=data.data;
                this.hideInputPassword();
                break;
            }
        }
    },
    //WiFi开启关闭按钮点击事件
    wifiSwitchChanged({checked}){
        this.wifiInfo.isActive=checked;
        if(checked){
            let wifistate=false;
            wifistate=wifi.enableWifi();
            if(!wifistate){
               prompt.showToast({
                   message:"wifi开启失败请重试",
                   duration:1500
               })
               this.wifiInfo.isActive=false;
               return;
            }
            this.wifiScaning();
        }else{
            this.wifiInfo.scanInfo=[];
            this.wifichecked={}
            wifi.disableWifi();
        }
    },
    //下拉刷新WiFi列表
    refreshTouched({state}){
        if(state=="start" && this.wifiInfo.isActive)
            this.wifiScaning();
    },
    //扫描wifi
    wifiScaning:async  function(){
        this.isScaning=true;
        wifi.scan();
        await wifi.getScanInfos((result)=>{
            let ss=JSON.parse(JSON.stringify(result));
            prompt.showToast({
                message:"获取到wifi扫描列表,当前共有"+ss.filter(t=>t.ssid).length+"个wifi",
                duration:1500
            })
            this.wifiInfo.scanInfo=ss;
            this.isScaning=false;
        });
    },
    //选中wifi弹出输入密码框
    checkedWifi(data){
        this.wifichecked=data.detail;
        this.showInputPassword();
    },
    //连接按钮事件
    connect(){
        this.connectWifi();
    },
    //连接wifi
    connectWifi(){
        let WifiDeviceConfig={
            ssid:this.wifichecked.ssid,
            bssid:this.wifichecked.bssid,
            preSharedKey:this.wifiPassword,
            isHiddenSsid:false,
            securityType:this.wifichecked.securityType
        }
        let status= wifi.connectToDevice(WifiDeviceConfig);
        console.log(`wifi指令下发状态：${status}`)
        if(status){

        }else{

        }
    },
    //显示键盘
    showKeyBoard(){
        this.$element("keyboard_dialog").show();
    },
    //关闭键盘显示
    hideKeyBoard(){
         this.$element("keyboard_dialog").close();
    },
    //显示输入WiFi密码
    showInputPassword(){
        this.wifiPassword='';
        this.isKeyBoradShow=true;
        if(this.isItemMoved)
            return;
        this.$element("wifi_dialog").show();
    },
    //关闭输入WiFi密码
    hideInputPassword(){
        this.isKeyBoradShow=false
        this.$element("keyboard_dialog").close();
        this.$element("wifi_dialog").close();
    },
    //键盘回调事件
    keyboardChange(value){
        this.wifiPassword= value.detail
    },
    //列表下拉滚动事件，当滚动时阻止弹出显示WiFi密码
    itemMoved(evt){
        this.isItemMoved=true;
    },
    //恢复状态
    listItemToucheStart(){
        this.isItemMoved=false;
    },
    onDestroy(){
        this.unSubscriberListener();
    }
}



